/*
    Space Simulation - Simulate the solar system
    Copyright (C) 2010  Guillaume Andrieu and Sylvain Martin

    This file is part of Space Simulation.

    Space Simulation is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Space Simulation is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Space Simulation.  If not, see <http://www.gnu.org/licenses/>.
 */
 
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#include "Particule.h"
#include "Vector3D.h"
#include "Simulation.h"
#include "physic.h"
#include "display/display.h"
#include "CSV.h"

int
main (int argc, char ** argv)
{
  Space space;
  space.G = 6.67428E-11;
  space.time = 0.0;
  
  double step_time,speed;
  char filename[FILENAME_MAX];
  FILE * csv_file;
  int err;
  
  /*
   * Options en ligne de commande
   */
  if(argc < 2)
  {
    printf("Erreur ! \nUtilisation : %s solar_system.csv [OPTIONS]\nVoir README.space_simulation pour plus de details\n", argv[0]);
    return -1;
  }
  
  step_time = -1.0;
  speed = -1.0;
  int winx = 0, winy = 0;
  
  /* Lecture des options */
  
  int i;
  for(i = 2; i < argc; i++)
  {
    if(strcmp(argv[i], "--step_time") == 0 && argc > i)
      step_time = atof(argv[i+1]);
    else if(strcmp(argv[i], "--speed") == 0 && argc > i)
      speed = atof(argv[i+1]);
    else if(strcmp(argv[i], "--win_x") == 0 && argc > i)
      winx = atoi(argv[i+1]);
    else if(strcmp(argv[i], "--win_y") == 0 && argc > i)
      winy = atoi(argv[i+1]);
  }
  
  /* Valeurs par defaut */
  
  if(step_time < 0.0)
      step_time = 86400.0;
  if(speed < 0.0)
    speed = 5.0E6;
  if(winx <= 0)
    winx = 600;
  if(winy <= 0)
    winy = 600;
    
  simul = MakeSimulation(space, 1288911600.0, step_time, speed);

  /* Lecture du fichier CSV */    
  strcpy(filename, argv[1]);
  csv_file = fopen(filename, "r");
    
  if(csv_file == NULL)
  {
    printf("Fichier introuvable ou non lisible ! \n");
    return -1;
  }
  
  /* Ajout des particules */
  Particule object;
  char line[1024];
  while( fscanf(csv_file, "%s", line) != EOF )
  {
    object = make_particule_from_csv(line, &err, NULL);
    if(err == 0)
      addParticule(&simul, object);
  }
    
  fclose(csv_file);

  display_init(&argc, argv);
  
  /* Echelle (m/pixel) */
  display_scale = 150.0/7.4067e+11;
  
  display_loop();
  
  return 0;
}
